<?php
namespace app\api\controller;
use think\Controller;
use think\Db;

class  Weixinshop extends Controller  {
    private $config=array( //改为1603445926的即可，key和证书还没有申请
        'APPID'              => 'wx46d4e28d5c894fce',
        'MCHID'              => '1614559248',
        'KEY'                => '5PrIT0ajjgN2vyzg4PfXuEQ1r4lPiUkM',
        'APPSECRET'          => '7cfdcb07d932eb89d8c98ad4cf8c2c8b',
        'NOTIFY_URL'         => 'http://csdl.jintianjifen.cn/api/Weixinshop/huidiao',

    );
    public $body;
    public $total_fee;
    public $out_trade_no;


    public function __construct($config=null){
        if (!empty($config)) {
            $this->config=$config;
        }
    }

    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }


    public function WeChatPayReady($order,$type=null){
        $weixinpay_config=$this->config;
        $config=array(
            'appid'=>$weixinpay_config['APPID'],
            'mch_id'=>$weixinpay_config['MCHID'],
            'nonce_str'=>'test',
            'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
            'notify_url'=>$weixinpay_config['NOTIFY_URL']
        );
        if(!empty($type)){
            $config['notify_url']='http://csdl.jintianjifen.cn/api/Weixinshop/huidiao';
        }
        $data=array_merge($order,$config);
        $sign=$this->makeSign($data);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $header[] = "Content-type: text/xml";
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        $result=$this->toArray($response);
        $result['sign']=$sign;
        $result['nonce_str']='test';
        $result2 = $this->getOrder($result['prepay_id']);
        return $result2;
    }


    public function getDateBytimeDate($string){
        $replacement = '-';
        $replacement2 = ':';
        $a = substr_replace($string, $replacement, 4, 0);
        $b = substr_replace($a, $replacement, 7, 0);
        $c = substr_replace($b, ' ', 10, 0);
        $d = substr_replace($c, $replacement2, 13, 0);
        $e = substr_replace($d, $replacement2, 16, 0);
        return $e;
    }

    public function write_admin_log($data)
    {
        file_put_contents ( APP_PATH."api/controller/wxpay_shop_log.txt", date ( "Y-m-d H:i:s" ) . "  " . $data . "\r\n", FILE_APPEND );
    }

    public function huidiao(){
        $xml=file_get_contents('php://input');
        $getInfo=$this->toArray($xml);
        $this->write_admin_log("response: ".var_export($getInfo,true));
        $data_sign=$getInfo['sign'];
        unset($getInfo['sign']);
        $sign=$this->makeSign($getInfo);
        if ($sign===$data_sign && $getInfo['return_code']=='SUCCESS' && $getInfo['result_code']=='SUCCESS') {
            Db::startTrans ();
            try{
                $num = $getInfo['out_trade_no'];
                $time = $this->getDateBytimeDate("{$getInfo['time_end']}");
                $info = Db::name('order')->where('o_order_num',$num)->find();
                switch($getInfo['attach']){
                    case 'balanceUp':
                        Db::name('shop')->where('shop_id',$info['o_shop_id'])->setInc ('shop_balance',$info['o_money']);
                        break;
                    case 'cashPledge':
                        $dai = Db::name('shop s')
                            ->join('admin a','s.shop_superior_agent = a.id','left')
                            ->where('shop_id',$info['o_shop_id'])
                            ->field('id,integral')
                            ->find();
                        Db::name('admin')->where('id',$dai['id'])->setDec ('integral',$info['o_jifen']);
                        Db::name('shop')->where('shop_id',$info['o_shop_id'])->setInc ('shop_integral',$info['o_jifen']);
                        Db::name('shop')->where('shop_id',$info['o_shop_id'])->setInc ('shop_pledge_money',$info['o_money']);
                        break;
                }
                Db::name ('order')->where ('o_order_num' , $num)->update (['o_pay_status' => 2 , 'o_third_order_num' => $getInfo[ 'transaction_id' ]]);
                Db::name('admin')->where('id',1)->setInc ('balance',$getInfo['total_fee']/100 );
                Db::commit ();
            }catch (\Exception $e){
                Db::rollback ();
            }
            $result = true;
        }else{
            $result=false;
        }
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
    }


    public function makeSign($data){
        $data=array_filter($data);
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        $config=$this->config;
        $string_sign_temp=$string_a."&key=".$config['KEY'];
        $sign = md5($string_sign_temp);
        $result=strtoupper($sign);
        return $result;
    }


    public function toArray($xml){
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }


    public function toXml($data){
        if(!is_array($data) || count($data) <= 0){
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }



    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";

            }
            else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }


    public function postXmlCurl($xml,$url,$second=30)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);
        if($data)
        {
            curl_close($ch);
            return $data;
        }
        else
        {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }

    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];
        }

        return $str;
    }


    public function getOrder($prepayId){
        $data["appid"] = $this->config["APPID"];
        $data["noncestr"] = $this->getRandChar(32);
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config['MCHID'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->makeSign($data, false);
        $data["sign"] = $s;

        return $data;
    }


    public  function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }

    public function userTiXian(){
        $refundNo = time();$openid='oTW1h1aa0S2O2R-JHUyH6TzR1x2E';$money=100;
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        $config_data = [
            'mch_appid' => $this->config['APPID'],
            'mchid' => $this->config['MCHID'],
            'nonce_str' => $this->getRandChar(32),
            'partner_trade_no' => $refundNo,
            'openid' => $openid,
            'check_name' => "NO_CHECK",
//            're_user_name' => $name,
            'amount' =>  (int)($money*100),
            'desc' => '支分宝转账',
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
        ];
        $sign = $this->makeSign($config_data);
        $config_data['sign'] = $sign;
        $xml = $this->toXml($config_data);
        $response = $this->httpRequest($url,$xml);
        dump($response);die;
        $result = $this->toArray($response);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            return ['status'=>200,'msg'=>$result['payment_no']];
        }else if($result['return_code'] == 'FAIL'){
            return ['status'=>100,'msg'=>$result['return_msg']];
        }else{
            if($result['err_code'] == 'SENDNUM_LIMIT'){
                return ['status'=>100,'msg'=>'单个用户每天最多可提现3次'];
            }
            return ['status'=>100,'msg'=>$result['err_code_des']];
        }
    }



    public function httpRequest($url, $postData = [])
    {
        $header[] = "Content-type: text/xml";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLCERT,ROOT_PATH.'/public/apiclient_cert2.pem');
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLKEY,ROOT_PATH.'/public/apiclient_key2.pem');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }

}